const axios = require('axios')
class UserController {
  // 搜索视频
  async get_video(ctx, next) {
    console.log("video");
    try {
      const { data } = await axios({
        url: 'https://m.v.qq.com/search.html',
        params: {
          keyWord: ctx.query.wd,
          act: 0
        }
      })
      let str = data.match(/class="search_item"[\s\S]*class="search_item"/ig)
      str = str[0].split("search_item")
      str.pop()
      str.shift()
      const body = str.map(res => {
        let title = res.match(/<strong[\s\S]*strong>/ig)
        let content = res.match(/<em\sclass="mask_txt">[\u4e00-\u9fa50-9]*/ig)
        let url = res.match(/figure[\s\S]{8}[a-zA-z]+:\/\/[^\s]*[A-Za-z0-9]/ig)
        if (url) { url = url[0].replace("figure\" href=\"", "") }
        if (content) {
          content = content[0] + "<\/em>"
        } else {
          content = ['暂无更新']
        }
        return { title: title[0], content, url }
      })
      ctx.body = {
        data: body,
        msg: "请求成功",
        code: 200
      }
    } catch (error) {
      ctx.body = {
        data: "未找到视频",
        msg: "请求失败",
        code: 404
      }
    }
  }
  // 搜索音乐 
  async get_music(ctx, next) {
    console.log("music:", ctx.query.wd)
    const apiUrl = `http://lite.tonzhon.com/api/search`

    const { data } = await axios({
      url: apiUrl,
      params: {
        provider: 'netease',
        keyword: ctx.query.wd
      }
    })
    const music = data.data.songs
    let musicLength = []
    for (let i in music) {
      const searchUrl = `http://lite.tonzhon.com/api/song_source/netease/${music[i].originalId}`
      const { data } = await axios({ url: searchUrl })
      musicLength = [...musicLength, {
        url: data.data.songSource,
        title: music[i].name,
        name: music[i].artists[0].name
      }]
    }
    ctx.body = musicLength
  }
}

module.exports = new UserController()